<template>
  <a-card :bordered="false">
    <upload-modal ref="uploadModal" size="small" :url="url" @sync="search" :file-list="fileList"></upload-modal>
    <record-modal ref="recordModal" size="small" :url="url" @sync="search"></record-modal>

    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter="search">
        <a-row :gutter="24">
          <a-col :md="8" :sm="8">
            <a-form-item label="模板类型">
                <a-select allowClear showSearch placeholder="请选择模板类型"
                          v-model:value="queryParam.id_template_type" :options="template_types">
                </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="9" :sm="9">
            <a-form-item label="模板搜索">
              <a-input placeholder="请输入关键字" v-model:value="queryParam.fileName"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="2" :sm="2"  >
            <a-form-item>
              <a-button v-show="selectedRowKeys.length > 0 && currentUser.isAdmin" @click.prevent="deleteMany" type="primary" danger>删除</a-button>
            </a-form-item>
          </a-col>
          <a-col :md="2" :sm="2" >
            <a-form-item>
              <a-button @click.prevent="search" type="default">查询</a-button>
            </a-form-item>
          </a-col>
          <a-col :md="2" :sm="2" :offset="1">
            <a-form-item>
              <a-button type="primary" @click="handleAdd">
                <PlusOutlined />{{templateType && templateType.category === 'oss' ? '上传' : '新增'}}
              </a-button>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a
          style="font-weight: 600">{{selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>
      <a-table
          size="small"
          bordered
          :rowKey="rowKey"
          :columns="columns"
          :dataSource="dataSourceFiltered"
          :pagination="pagination"
          :loading="loading"
          :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
          @change="handleTableChange">

        <template #action="{ record }">
            <a @click="deleteOne(record)" >删除</a>
            <a-divider type="vertical"/>
          <a-dropdown>
            <a class="ant-dropdown-link" @click.prevent>更多<DownOutlined /></a>
            <template #overlay>
              <a-menu>
                <a-menu-item  @click="modify(record)">
                  {{templateType.category !== 'oss' ? '修改' : '参数配置'}}
                </a-menu-item>
                <a-menu-item v-if="templateType.category === 'oss'" @click="handleDownload(record)">
                  下载
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </template>
      </a-table>
    </div>

  </a-card>
</template>

<script setup>
import { ref, computed, onMounted, createVNode } from 'vue';
import { deleteAction, downFile, getAction, postAction, putAction } from "@/utils/request";
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import _ from 'lodash';
import UploadModal from '@/views/modules/UploadModal.vue';
import RecordModal from '@/views/modules/RecordModal.vue';
import { message, Modal } from 'ant-design-vue';
import useUserStore from '@/store/modules/user'

// dict
const currentUser = useUserStore()
// data
const rowKey = ref('id')
const selectedRowKeys = ref([]);
const selectedRows = ref([]);
const loading = ref(false);
// 定义响应式数据
const description = ref('样式模板配置');
const previewVisible = ref(false);
const previewImage = ref('');
const template_types = ref([]);
const bucketName = ref('waybill');
const fileList = ref([]);
const field = ref('create_time');
const order = ref('descend');
const columns_config = ref([
  {
    title: '#', dataIndex: '', key: 'rowIndex', width: "2%", align: "center",
    customRender: ({text, record, index}) => parseInt(index) + 1
  },
  {
    title: '导出模板名称', align: "left", sorter: true, width: '20%', dataIndex: 'name'
  },
  {
    title: '配置内容', align: "center", sorter: true, width: '36%', dataIndex: 'config'
  },
  {
    title: '说明', align: "center", width: '20%', dataIndex: 'description'
  },
  {
    title: '创建日期', align: "center", sorter: true, width: '9%', dataIndex: 'create_time',
    customRender: ({text:t}) => t
  },
  {
    title: '操作', width: '9%', dataIndex: 'action', align: "center",
    slots: { customRender: 'action' }
  }
]);
const columns_oss = ref([
  {
    title: '#', dataIndex: '', key: 'rowIndex', width: "2%", align: "center",
    customRender: ({text, record, index}) => parseInt(index) + 1
  },
  {
    title: '模板文件名称', align: "left", sorter: true, width: '30%', dataIndex: 'fileName'
  },
  {
    title: '大小', align: "right", width: '4%', dataIndex: 'size',
    customRender: ({text:t}) => {
      let val = '';
      if (t >= 1024 * 1024) {
        val = _.round(t / (1024 * 1024)) + "M";
      } else if (t >= 1024) {
        val = _.round(t / 1024) + "K";
      } else {
        val = t + "b";
      }
      return val;
    }
  },
  {
    title: '备注', align: "left", sorter: true, width: '30%', dataIndex: 'memo'
  },
  {
    title: '配置内容', align: "center", sorter: true, width: '16%', dataIndex: 'config'
  },
  {
    title: '创建日期', align: "center", sorter: true, width: '9%', dataIndex: 'create_time'
  },
  {
    title: '操作', width: '9%', dataIndex: 'action', align: "center", slots: { customRender: 'action' }
  }
]);

const dataSource = ref([]);
const data = reactive({
  queryParam:{
    id_template_type: undefined,
    fileName: ''
  },
  pagination:{
    "current": 1,
    "pageSize": 10,
    "pageSizeOptions": ["10", "20", "30", "50", "100"],
    "showQuickJumper": true,
    "showSizeChanger": true,
    "total": 0
  }
 })
const {queryParam, pagination} = toRefs(data);
// 定义组件引用
const uploadModal = ref(null);
const recordModal = ref(null);
///simple vars
const url = {
  getDataBySql: '/sys/getDataBySql',
  template: '/yg/template',
  template_type: '/yg/template_type',
  oss: "/oss/",
  list: "/oss/",
  delete: "/oss/"
};
const sql = {
  template_type: 'select id, code as value, name as label, category from "YG_TemplateType"'
}

// 计算属性
const bizPath = computed(() => `${queryParam.value.id_template_type}/templates/`);
const templateType = computed(() => template_types.value.find((i) => i.value === queryParam.value.id_template_type));
const columns = computed(() => {
  dataSource.value = [];
  if (templateType.value && templateType.value.category === "json") {
    return columns_config.value;
  } else {
    return columns_oss.value;
  }
});
const uploadAction = computed(() => url.oss);
const dataSourceFiltered = computed(() => {
  let data = dataSource.value;
  if (queryParam.value.fileName) {
    data = data.filter((d) =>
      (d.filePath && d.filePath.indexOf(queryParam.value.fileName) !== -1) ||
      (d.memo && d.memo.indexOf(queryParam.value.fileName) !== -1)
    );
  }
  if (data) pagination.value.total = data.length;
  return data;
});

// 方法
const handleAdd = () => {
  if (checkBeforeUpload()) {
    let record = {
      bizPath: bizPath.value,
      bucketName: bucketName.value,
      template_type_id: templateType.value?.id,
      create_by: currentUser.name,
      update_by: currentUser.name
    };
    if (templateType.value && templateType.value.category === 'oss') {
        fileList.value.length = 0;
        uploadModal.value?.add(record);
    } else {
        recordModal.value?.add(record);
    }
  }
};

const modify = (record) => {
  if (templateType.value?.category === "oss") {
    editMemo(record);
  } else {
    record.template_type_id = templateType.value?.id;
    recordModal.value?.edit(record);
  }
};

const onSelectChange = (newSelectedRowKeys, newSelectedRows) => {
  console.log(JSON.stringify(newSelectedRows))
  selectedRowKeys.value = newSelectedRowKeys;
  selectedRows.value = newSelectedRows;
};

const handleDownload = (params) => {
  params.bucketName = bucketName.value;
  downFile(`${url.oss}download`, { ...params }).then((data) => {
    if (!data) {
      message.warning("文件下载失败");
      return;
    }
    if (typeof window.navigator.msSaveBlob !== 'undefined') {
      window.navigator.msSaveBlob(new Blob([data]), params.fileName);
    } else {
      const urlObject = window.URL.createObjectURL(new Blob([data]));
      const link = document.createElement('a');
      link.style.display = 'none';
      link.href = urlObject;
      link.setAttribute('download', params.fileName);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(urlObject);
    }
  }).catch((error) => {
    console.error("error:", error);
    if (error.response && error.response.status === 404) {
      message.warning("文件未找到或请求地址不正确！！");
    }
  });
};

const search = () => {
  if (!templateType.value) {
      message.error('请先选择样式模板类型！');
      return false;
  }
  if (templateType.value.category === 'oss') {
      rowKey.value = 'filePath';
      getOssFiles();
  } else {
      rowKey.value = 'id';
      getTemplateConfig();
  }
};

const handleTableChange = (newPagination, filters, sorter) => {
  pagination.value = newPagination;
  if (sorter) {
    field.value = sorter.field.replace("fileName","filePath");
    order.value = sorter.order;
  }
  search();
};

const checkBeforeUpload = () => {
  if (!queryParam.value.id_template_type) {
    message.error('请先选择模板类型！');
    return false;
  }
  fileList.value=[]
  return true;
};

const getTemplateConfig = () => {
  loading.value = true;
  getAction(url.template, {}).then((res) => {
    if (res && res.success && Array.isArray(res.data)) {
      res.data.sort((a, b) => {
        if (order.value === 'descend') {
          return a[field.value] < b[field.value] ? -1 : a[field.value] > b[field.value] ? 1 : 0;
        } else {
          return a[field.value] < b[field.value] ? 1 : a[field.value] > b[field.value] ? -1 : 0;
        }
      });
      dataSource.value = [...res.data];
      loading.value = false;
    }
  });
};

const getOssFiles = () => {
  loading.value = true;
  getAction(url.oss, {
    bucketName: bucketName.value,
    bizPath: bizPath.value
  }).then((res) => {
    if (res && res.success && Array.isArray(res.data)) {
      res.data.sort((a, b) => {
        if (order.value === 'descend') {
          return a[field.value] < b[field.value] ? -1 : a[field.value] > b[field.value] ? 1 : 0;
        } else {
          return a[field.value] < b[field.value] ? 1 : a[field.value] > b[field.value] ? -1 : 0;
        }
      });
      res.data.forEach((value) => {
        let filepath = value.filePath;
        if (filepath) {
          filepath = filepath.split("/").pop();
        }
        value.fileName = filepath;
      });
      dataSource.value = [...res.data];
      loading.value = false;
    }
  });
};

const get_template_type = () => {
  postAction(url.getDataBySql, { sql: sql.template_type }).then((res) => {
    if (res && res.success && Array.isArray(res.data)) {
        template_types.value = res.data.filter((value) => {
                return value.category !== 'json' || currentUser.isAdmin;
              }).map((value) => ({
                id: value.id,
                key: value.value,
                label: value.label,
                value: value.value,
                category: value.category
              }));
      }
      //console.error("template_types:",JSON.stringify(template_types.value))
  });
};

const editMemo = (record) => {
  fileList.value = [];
  uploadModal.value?.edit(record, '参数配置');
};

const deleteMany = () => {
  Modal.confirm({
    title: () => "确认删除",
    icon: () => createVNode(ExclamationCircleOutlined),
    content: "是否删除选中文件?",
    onOk() {
      if (templateType.value?.category === "oss") {
        const filePaths = selectedRowKeys.value
        deleteAction(url.oss, { bucketName: bucketName.value}, {filePaths}).then((res) => {
          if (res.success) {
            selectedRows.value = [];
            selectedRowKeys.value = [];
            getOssFiles();
          } else {
            message.error(`删除失败！`);
          }
        });
      } else {
        const template_ids = selectedRows.value.map((s) => s.id);
        deleteAction(url.template, {}, { id: template_ids }).then((res) => {
          if (res.success) {
            selectedRows.value = [];
            selectedRowKeys.value = [];
            getTemplateConfig();
          } else {
            message.error(`删除失败！`);
          }
        });
      }
    },
    onCancel() {},
  });
};

const deleteOne = (record, callback) => {
  Modal.confirm({
    title: ()=>"确认删除",
    content: "是否删除此文件?",
    onOk: () => {
      if (templateType.value?.category === "oss") {
        deleteAction(url.oss, { bucketName: bucketName.value, filePath: record.filePath }).then((res) => {
          if (res.success) getOssFiles();
          if (callback && typeof callback === 'function') callback();
        });
      } else {
        deleteAction(url.template, {}, { id: [record.id] }).then((res) => {
          if (res.success) getTemplateConfig();
          if (callback && typeof callback === 'function') callback();
        });
      }
    }
  });
};

const onClearSelected = () => {
  selectedRowKeys.value = [];
  selectedRows.value = [];
};

const searchQuery = () => {
  search();
};

// 生命周期钩子
onMounted(() => {
  get_template_type();
});
</script>

